//
//  LLSearchResultViewController.m
//  LLSearchView
//
//  Created by 王龙龙 on 2017/7/25.
//  Copyright © 2017年 王龙龙. All rights reserved.
//搜索结果VC

#import "LLSearchResultViewController.h"
#import "BYserverModel.h"//瀑布流的Model
#import "BYcitizenModel.h"//导览页和搜索页cell的model
#import "BYTableViewCell.h"//导览页和搜索页tabviewcell
#import "OneCollectionViewCell.h"//瀑布流的cell

@interface LLSearchResultViewController ()<UIGestureRecognizerDelegate,UISearchBarDelegate,UITableViewDelegate,UITableViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource>
/**搜索框*/
@property (nonatomic, strong) UISearchBar *searchBar;
/**无结果的提示label*/
@property (nonatomic,strong) UILabel *noDataLab;
/**服务的瀑布流*/
@property (nonatomic, strong) UICollectionView *collectioneView;
/**瀑布流的头部View*/
@property (nonatomic,strong) UIView *headerView;
/**上方服务瀑布流的数据源数组*/
@property (nonatomic, strong) NSMutableArray *collectionDataArr;
/**搜索出的tableView*/
@property (nonatomic, strong) UITableView *mainTableView;
/**tableView的数据源数组*/
@property (nonatomic, strong) NSMutableArray *infoDataArray;

@end
@implementation LLSearchResultViewController
#pragma mark- init初始化
- (void)viewDidLoad{
    [super viewDidLoad];
    [self setBarButtonItem];
    [self requestSearchResultData];
    [self pd_addReturnKeyBoard];
    [self.view addSubview:self.collectioneView];
    [self.view addSubview:self.mainTableView];
    [self.view addSubview:self.noDataLab];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (!self.tabBarController.tabBar.isHidden) {
        self.tabBarController.tabBar.hidden = YES;
    }
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    // 回收键盘
    [self.searchBar resignFirstResponder];
    self.navigationController.navigationBarHidden=NO;
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.searchBar resignFirstResponder];
}
- (void)setBarButtonItem{
    self.view.backgroundColor = [UIColor whiteColor];
    [self.navigationItem setHidesBackButton:YES];
    // 创建搜索框
//    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(5, 7, self.view.frame.size.width, 30)];
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 5, self.view.frame.size.width - 15, 20)];
    searchBar.placeholder = self.searchStr;
    searchBar.delegate = self;
    searchBar.showsCancelButton = YES;
    searchBar.barStyle = UISearchBarStyleMinimal;
    UIView *searchTextField = searchTextField = [searchBar valueForKey:@"_searchField"];
    searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
    [searchTextField setBackgroundColor:[UIColor whiteColor]];
    searchTextField.layer.cornerRadius = 14.0f;
    searchTextField.layer.borderColor = RGBA(152, 152, 152, 1).CGColor;
    searchTextField.layer.borderWidth = 1;
    searchTextField.layer.masksToBounds = YES;
    [searchBar setImage:[UIImage imageNamed:@"sort_magnifier"] forSearchBarIcon:UISearchBarIconSearch state:UIControlStateNormal];
    UIButton *cancleBtn = [searchBar valueForKey:@"cancelButton"];
    //修改标题和标题颜色
    [cancleBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancleBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [titleView addSubview:searchBar];
    self.searchBar = searchBar;
    [self.searchBar becomeFirstResponder];
    self.navigationItem.titleView = searchBar;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:nil];
}
- (UILabel *)noDataLab{
    if (!_noDataLab) {
        _noDataLab = [[UILabel alloc]initWithFrame:CGRectMake(0,(KSCREEHEGIHT-BY_Nav_H)/2-10, KSCREEWIDTH, 30)];
        _noDataLab.textAlignment = NSTextAlignmentCenter;
        _noDataLab.text = @"抱歉，未找到您想要的，换个词试试";
        _noDataLab.textColor = RGBA(152, 152, 152, 1);
        _noDataLab.font = H14;
        _noDataLab.hidden = YES;
    }
    return _noDataLab;
}
- (UICollectionView *)collectioneView{
    if (!_collectioneView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(100, 70);
        //设置collectionView滚动方向
        _collectioneView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, BY_Nav_H, BY_ScreenWidth, 130) collectionViewLayout:layout];
        _collectioneView.showsVerticalScrollIndicator = NO;
        _collectioneView.backgroundColor =  [UIColor clearColor];
        [self.collectioneView registerClass:[OneCollectionViewCell class] forCellWithReuseIdentifier:@"OneCollectionViewCell"];
        _collectioneView.showsHorizontalScrollIndicator= NO;
        _collectioneView.delegate = self;
        _collectioneView.dataSource = self;
        layout.headerReferenceSize=CGSizeMake(self.view.frame.size.width, 40);
        [_collectioneView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerViewIdentifier"];
    }
    return _collectioneView;
}
- (UITableView *)mainTableView{
    if (!_mainTableView) {
        _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,130+BY_Nav_H, KSCREEWIDTH, KSCREEHEGIHT -130-BY_NavBot_H) style:UITableViewStylePlain];
        _mainTableView.delegate = self;
        _mainTableView.dataSource = self;
        _mainTableView.backgroundColor = [UIColor whiteColor];
        _mainTableView.tableFooterView = [UIView new];
        [_mainTableView registerClass:[BYTableViewCell class] forCellReuseIdentifier:@"BYTableViewCell"];
        [_mainTableView registerClass: [UITableViewHeaderFooterView class] forHeaderFooterViewReuseIdentifier:@"headv"];
    }
    return _mainTableView;
}

#pragma mark-用户交互
- (void)pd_addReturnKeyBoard {//给当前view添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewKeyBoardHiddenClick)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
}
- (void)viewKeyBoardHiddenClick{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.window endEditing:YES];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
//    NSLog(@"%@",NSStringFromClass([touch.view class]));
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {//判断如果点击的是tableView的cell，就把手势给关闭了
        return NO;//关闭手势
    }//否则手势存在
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UIView"]) {//判断如果点击的是tableView的cell，就把手势给关闭了
        return NO;//关闭手势
    }
    return YES;
}

#pragma mark - UISearchBarDelegate
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{//点击了键盘上的搜索按钮
    [self.searchBar resignFirstResponder];
    self.searchStr = searchBar.text;
    [self requestSearchResultData];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    [self.searchBar resignFirstResponder];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = YES;
}


#pragma mark- UICollectionView处理
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.collectionDataArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    OneCollectionViewCell *cell = (OneCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:@"OneCollectionViewCell" forIndexPath:indexPath];
    [cell setBYserverModel:self.collectionDataArr[indexPath.row]];
    return cell;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    UICollectionReusableView *headerView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"headerViewIdentifier" forIndexPath:indexPath];
    [self addCollectionViewHeadContent:[NSString stringWithFormat:@"%@ - 服务",self.searchStr]];
    //头视图添加view
    [headerView addSubview:self.headerView];
    return headerView;
}
- (void)addCollectionViewHeadContent:(NSString *)str{//设置头部内容
    UILabel *header=[[UILabel alloc]init];
    header.frame=CGRectMake(8, 0, self.view.frame.size.width, 40);
    header.backgroundColor = [UIColor whiteColor];
    header.textAlignment = NSTextAlignmentLeft;
    header.text = str;
    header.textColor = RGBA(152, 152, 152, 1);
    header.font = H14;
    self.headerView=header;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    BYserverModel *model =self.collectionDataArr[indexPath.row];
    NSDictionary *statisticDict = @{@"uuid":[SaveCacheData loadDataStrWithKey:currentUserudid]==NULL?@"none":[SaveCacheData loadDataStrWithKey:currentUserudid],@"time":@([[self getNowTimeTimestamp] integerValue]),@"mid":model.mid,@"type":@([self collectionItemType:model.type])};
    [self requestOpenMuneStatistics:statisticDict];
    if(model.type == 3){//小程序
        BOOL isWX = [WXApi isWXAppInstalled];//是否安装微信（YES已安装、NO未安装)
        if (isWX) {
            NSDictionary *dict = [self dictionaryWithJsonString:[model.url stringByReplacingOccurrencesOfString:@"\n" withString:@""]];
            WXLaunchMiniProgramReq *launchMiniProgramReq = [WXLaunchMiniProgramReq object];
            launchMiniProgramReq.userName = dict[@"userName"];  //拉起的小程序的username
            launchMiniProgramReq.path =  dict[@"path"];;    //拉起小程序页面的可带参路径，不填默认拉起小程序首页
            launchMiniProgramReq.miniProgramType = WXMiniProgramTypeRelease; //拉起小程序的类型
            [WXApi sendReq:launchMiniProgramReq];
        }else{
            NSString *xcxUrl = @"";
            if ([model.mid isEqualToString:@"jinpaijieshuo"]) {//金牌解说
                xcxUrl = noWeChatJieShuo;
            }else if ([model.mid isEqualToString:@"yunFoodBooking"]){//智慧食堂
                xcxUrl = noWeChatShiTang;
            }else{
            }
            BYWebVC *webVC = [[BYWebVC alloc]init];
            webVC.url = xcxUrl;
            webVC.titleStr = model.name;
            [self.navigationController pushViewController:webVC animated:YES];
        }
    }else{
        BYWebVC *webVC = [[BYWebVC alloc]init];
        webVC.url = model.url;
        webVC.titleStr = model.name;
        [self.navigationController pushViewController:webVC animated:YES];
    }
}
- (NSString *)getNowTimeTimestamp{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss SSS"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[datenow timeIntervalSince1970]*1000];
    return timeSp;
}
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&err];
    if(err){
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
- (NSInteger )collectionItemType:(NSInteger)type{
    if (type ==0 ||type ==2 ) {
        return 1;
    }else{
        return 2;
    }
}

#pragma mark- UITableView处理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.infoDataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BYTableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:@"BYTableViewCell" forIndexPath:indexPath];
    if (self.infoDataArray.count!=0) {
        BYcitizenModel *model = self.infoDataArray[indexPath.row];
        [cell setBYcitizenModel:model];
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return BY_Width(164)+BY_Height(40);;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    //如果是头视图
    UITableViewHeaderFooterView* headV=[tableView dequeueReusableHeaderFooterViewWithIdentifier:@"headv"];
    headV.contentView.backgroundColor = [UIColor whiteColor];
    headV.textLabel.text = [NSString stringWithFormat:@"%@ - 咨询信息",self.searchStr];
    headV.textLabel.textAlignment = NSTextAlignmentLeft;
    headV.textLabel.textAlignment = NSTextAlignmentLeft;
    headV.textLabel.textColor = RGBA(152, 152, 152, 1);
    headV.textLabel.font = H14;
    return headV;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BYcitizenModel*model =self.infoDataArray[indexPath.row];
    for (BYSetModel *models in APPDELEGATE.SetDataArray) {
        if ([models.setting_name isEqualToString:@"guide-travel-detail"]) {
            NSString *urlStr = models.setting_value;
            NSString *paramStr = [NSString stringWithFormat:@"id=%@&userid=%@&token=%@",model.material_uid,[SaveCacheData loadDataStrWithKey:currentUserudid] ==nil?@"":[SaveCacheData loadDataStrWithKey:currentUserudid],[SaveCacheData loadDataStrWithKey:currentUserToken] ==nil?@"":[SaveCacheData loadDataStrWithKey:currentUserToken]];
            NSString *webURL= @"";
            if ([urlStr rangeOfString:@"?"].location == NSNotFound) {//没有?参数
                webURL = [NSString stringWithFormat:@"%@?%@",urlStr,paramStr];
            } else {//有参数
                webURL = [NSString stringWithFormat:@"%@&%@",urlStr,paramStr];
            }
            BYWebVC *VC = [[BYWebVC alloc]init];
            VC.url = webURL;
            [self.navigationController pushViewController:VC animated:YES];
        }
    }
}

#pragma mark- 网络请求
- (void)requestSearchResultData{
    NSDictionary *dict = @{@"keyword":self.searchStr};
    [BYNetworking requestGetOrPostWithType:GET url:LJURL_search params:dict success:^(NSInteger code, NSString * _Nonnull msg, id  _Nonnull data) {
        NSArray *dataArrs = [data objectForKey:@"data"][@"infolist"];
        NSMutableArray *dataArrMs = [NSMutableArray arrayWithCapacity:dataArrs.count];
        for (NSDictionary *dics in dataArrs) {
            BYcitizenModel *topCarouselModel = [BYcitizenModel mj_objectWithKeyValues:dics];
            [dataArrMs addObject:topCarouselModel];
        }
        self.infoDataArray = dataArrMs.copy;
        NSArray *dataArr = [data objectForKey:@"data"][@"menulist"];
        NSMutableArray *dataArrM = [NSMutableArray arrayWithCapacity:dataArr.count];
        for (NSDictionary *dic in dataArr) {
            BYserverModel *topCarouselModel = [BYserverModel mj_objectWithKeyValues:dic];
            [dataArrM addObject:topCarouselModel];
        }
        self.collectionDataArr = dataArrM.copy;
        [self.mainTableView reloadData];
        [self.collectioneView reloadData];
        if (self.collectionDataArr.count ==0 && self.infoDataArray.count ==0) {
            self.noDataLab.hidden = NO;
        }
        if (self.collectionDataArr.count ==0) {
            self.collectioneView.hidden = YES;
            self.mainTableView.frame = CGRectMake(0,BY_Nav_H ,KSCREEWIDTH, KSCREEHEGIHT- BY_Nav_H);
        }
        if (self.infoDataArray.count ==0) {
            self.mainTableView.hidden = YES;
        }
    } fail:^(NSError * _Nonnull error) {
    } showHUD:YES];
}
- (void)requestOpenMuneStatistics:(NSDictionary *)dic{//点击item的统计
    [BYNetworking requestGetOrPostWithType:POST url:LJURL_open_mune params:dic success:^(NSInteger code, NSString * _Nonnull msg, id  _Nonnull data) {
    } fail:^(NSError * _Nonnull error) {
    } showHUD:YES];
}


@end
